#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use eframe::egui;
use std::time::{Duration, Instant};
use std::fs;
use std::path::Path;
use serde::{Deserialize, Serialize};
use rodio::{OutputStream, Sink};

// 引入主题配置模块
mod theme_config;
use theme_config::{ThemeManager, create_default_theme_manager};

#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
enum Preset {
    #[default]
    TwentyFiveFive,
    FortyFiveFifteen,
    Custom,
}

#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
enum Theme {
    #[default]
    MD3,
}

#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
enum ThemeMode {
    #[default]
    Light,
    Dark,
}

#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
enum TimerState {
    #[default]
    Stopped,
    Running,
    Paused,
}

// 配置结构体
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Config {
    pub theme: ThemeConfig,
    pub ui: UiConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ThemeConfig {
    #[serde(default = "default_theme_color")]
    pub default_color: String,
    #[serde(default = "default_theme_mode")]
    pub default_mode: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct UiConfig {
    #[serde(default = "default_time_display_size")]
    pub time_display_size: f32,
    #[serde(default = "default_status_text_size")]
    pub status_text_size: f32,
    #[serde(default = "default_button_height")]
    pub button_height: f32,
    #[serde(default = "default_button_width_ratio")]
    pub button_width_ratio: f32,
    #[serde(default = "default_body_font_size")]
    pub body_font_size: f32,
    #[serde(default = "default_heading_font_size")]
    pub heading_font_size: f32,
    #[serde(default = "default_button_font_size")]
    pub button_font_size: f32,
}

// 为ThemeConfig实现Default trait
impl Default for ThemeConfig {
    fn default() -> Self {
        Self {
            default_color: default_theme_color(),
            default_mode: default_theme_mode(),
        }
    }
}

// 为UiConfig实现Default trait
impl Default for UiConfig {
    fn default() -> Self {
        Self {
            time_display_size: default_time_display_size(),
            status_text_size: default_status_text_size(),
            button_height: default_button_height(),
            button_width_ratio: default_button_width_ratio(),
            body_font_size: default_body_font_size(),
            heading_font_size: default_heading_font_size(),
            button_font_size: default_button_font_size(),
        }
    }
}

// 默认配置值
fn default_theme_color() -> String { "red".to_string() }
fn default_theme_mode() -> String { "dark".to_string() }
fn default_time_display_size() -> f32 { 90.0 }
fn default_status_text_size() -> f32 { 36.0 }
fn default_button_height() -> f32 { 36.0 }
fn default_button_width_ratio() -> f32 { 0.3 }
fn default_body_font_size() -> f32 { 14.0 }
fn default_heading_font_size() -> f32 { 16.0 }
fn default_button_font_size() -> f32 { 14.0 }

impl Default for Config {
    fn default() -> Self {
        Self {
            theme: ThemeConfig {
                default_color: default_theme_color(),
                default_mode: default_theme_mode(),
            },
            ui: UiConfig {
                time_display_size: default_time_display_size(),
                status_text_size: default_status_text_size(),
                button_height: default_button_height(),
                button_width_ratio: default_button_width_ratio(),
                body_font_size: default_body_font_size(),
                heading_font_size: default_heading_font_size(),
                button_font_size: default_button_font_size(),
            },
        }
    }
}

impl Config {
    // 从文件加载配置
    pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
        let config_path = "config.toml";
        if Path::new(config_path).exists() {
            let content = fs::read_to_string(config_path)?;
            let config: Config = toml::from_str(&content)?;
            Ok(config)
        } else {
            // 如果配置文件不存在，创建默认配置文件
            let default_config = Config::default();
            default_config.save()?;
            Ok(default_config)
        }
    }
    
    // 保存配置到文件
    pub fn save(&self) -> Result<(), Box<dyn std::error::Error>> {
        let content = toml::to_string_pretty(self)?;
        fs::write("config.toml", content)?;
        Ok(())
    }
}

pub fn main() {
    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_inner_size([600.0, 800.0])
            .with_min_inner_size([400.0, 600.0])
            .with_icon(load_icon()),
        ..Default::default()
    };
    
    eframe::run_native(
        "米多计时",
        options,
        Box::new(|cc| {
            // 设置中文字体支持
            egui_zhcn_fonts::add_sys_ui_fonts(&cc.egui_ctx);
            
            // 初始化默认样式（将在每次更新时被自定义样式覆盖）
            Ok(Box::new(PomodoroApp::new()))
        }),
    ).expect("无法运行应用程序");
}

fn load_icon() -> egui::IconData {
    // 创建一个橙红色的对号符号图标
    let size = 32;
    let mut pixels = vec![0; size * size * 4];
    
    // Draw a more detailed checkmark
    // Orange-red color (RGB: 255, 102, 0)
    let orange_red = [255, 102, 0, 255]; // R, G, B, A
    
    // Draw the checkmark - from top left to bottom right
    // First segment: top left part (descending)
    for i in 0..6 {
        let x = 9 + i;
        let y = 15 + i;
        if x < size && y < size {
            let idx = (y * size + x) * 4;
            pixels[idx] = orange_red[0];     // R
            pixels[idx + 1] = orange_red[1]; // G
            pixels[idx + 2] = orange_red[2]; // B
            pixels[idx + 3] = orange_red[3]; // A
        }
        
        // Add thickness to the checkmark
        for dx in -1..=1 {
            for dy in -1..=1 {
                let nx = (9 + i) as i32 + dx;
                let ny = (15 + i) as i32 + dy;
                if nx >= 0 && nx < size as i32 && ny >= 0 && ny < size as i32 {
                    let nx = nx as usize;
                    let ny = ny as usize;
                    let idx = (ny * size + nx) * 4;
                    // Only set if not already set
                    if pixels[idx] == 0 && pixels[idx + 1] == 0 && pixels[idx + 2] == 0 {
                        pixels[idx] = orange_red[0];     // R
                        pixels[idx + 1] = orange_red[1]; // G
                        pixels[idx + 2] = orange_red[2]; // B
                        pixels[idx + 3] = orange_red[3]; // A
                    }
                }
            }
        }
    }
    
    // Second segment: bottom part (ascending)
    for i in 0..8 {
        let x = 13 + i;
        let y = 19 - i;
        if x < size && y < size {
            let idx = (y * size + x) * 4;
            pixels[idx] = orange_red[0];     // R
            pixels[idx + 1] = orange_red[1]; // G
            pixels[idx + 2] = orange_red[2]; // B
            pixels[idx + 3] = orange_red[3]; // A
        }
        
        // Add thickness to the checkmark
        for dx in -1..=1 {
            for dy in -1..=1 {
                let nx = (13 + i) as i32 + dx;
                let ny = (19 - i) as i32 + dy;
                if nx >= 0 && nx < size as i32 && ny >= 0 && ny < size as i32 {
                    let nx = nx as usize;
                    let ny = ny as usize;
                    let idx = (ny * size + nx) * 4;
                    // Only set if not already set
                    if pixels[idx] == 0 && pixels[idx + 1] == 0 && pixels[idx + 2] == 0 {
                        pixels[idx] = orange_red[0];     // R
                        pixels[idx + 1] = orange_red[1]; // G
                        pixels[idx + 2] = orange_red[2]; // B
                        pixels[idx + 3] = orange_red[3]; // A
                    }
                }
            }
        }
    }
    
    egui::IconData {
        rgba: pixels,
        width: size as u32,
        height: size as u32,
    }
}

pub struct PomodoroApp {
    work_minutes: u16,
    break_minutes: u16,
    current_time: Duration,
    is_running: TimerState,
    is_work_time: bool,
    preset: Preset,
    work_input: String,
    break_input: String,
    theme: Theme,
    theme_mode: ThemeMode,
    start_time: Option<Instant>,
    elapsed_at_pause: Duration,
    show_notification: bool,
    notification_title: String,
    notification_message: String,
    // Sound related fields
    _stream: Option<OutputStream>,
    sink: Option<Sink>,
    volume: f32,
    // Exit flag
    should_exit: bool,
    // Animation fields
    start_button_hover: bool,
    pause_button_hover: bool,
    reset_button_hover: bool,
    last_update: Option<Instant>,
    // Button animation fields
    start_button_press: bool,
    pause_button_press: bool,
    reset_button_press: bool,
    // Custom settings visibility
    show_custom_settings: bool,
    // Configuration
    config: Config,
    // UI parameters from config
    time_display_size: f32,
    status_text_size: f32,
    button_height: f32,
    button_width_ratio: f32,
    body_font_size: f32,
    heading_font_size: f32,
    button_font_size: f32,
    // 主题管理器
    theme_manager: ThemeManager,
}

impl PomodoroApp {
    fn new() -> Self {
        // Load configuration
        let config = Config::load().unwrap_or_default();
        
        // Initialize theme based on config
        let theme = Theme::MD3; // 只使用MD3主题
        
        let theme_mode = match config.theme.default_mode.as_str() {
            "dark" => ThemeMode::Dark,
            _ => ThemeMode::Light, // default to light
        };
        
        // Initialize UI parameters from config
        let time_display_size = config.ui.time_display_size;
        let status_text_size = config.ui.status_text_size;
        let button_height = config.ui.button_height;
        let button_width_ratio = config.ui.button_width_ratio;
        let body_font_size = config.ui.body_font_size;
        let heading_font_size = config.ui.heading_font_size;
        let button_font_size = config.ui.button_font_size;
        
        // 初始化主题管理器
        let theme_manager = create_default_theme_manager();
        
        // Initialize audio system with proper error handling
        let audio_result = OutputStream::try_default();
        let (_stream, sink) = match audio_result {
            Ok((stream, stream_handle)) => {
                match Sink::try_new(&stream_handle) {
                    Ok(sink) => (Some(stream), Some(sink)),
                    Err(err) => {
                        eprintln!("Warning: Failed to create audio sink: {}", err);
                        (Some(stream), None)
                    }
                }
            }
            Err(err) => {
                eprintln!("Warning: Failed to initialize audio output: {}", err);
                (None, None)
            }
        };
        
        Self {
            work_minutes: 25,
            break_minutes: 5,
            current_time: Duration::from_secs(25 * 60),
            is_running: TimerState::Stopped,
            is_work_time: true,
            preset: Preset::TwentyFiveFive,
            work_input: "25".to_string(),
            break_input: "5".to_string(),
            theme,
            theme_mode,
            start_time: None,
            elapsed_at_pause: Duration::new(0, 0),
            show_notification: false,
            notification_title: String::new(),
            notification_message: String::new(),
            _stream,  // This is the Option<OutputStream>
            sink,     // This is the Option<Sink>
            volume: 0.5, // Default volume at 50%
            should_exit: false,
            // Initialize animation fields
            start_button_hover: false,
            pause_button_hover: false,
            reset_button_hover: false,
            last_update: None,
            // Button animation fields
            start_button_press: false,
            pause_button_press: false,
            reset_button_press: false,
            // Custom settings visibility
            show_custom_settings: false,
            // Configuration
            config,
            // UI parameters from config
            time_display_size,
            status_text_size,
            button_height,
            button_width_ratio,
            body_font_size,
            heading_font_size,
            button_font_size,
            // 主题管理器
            theme_manager: theme_manager.expect("Failed to load theme manager"),
        }
    }
    
    // 从配置文件重新加载配置
    fn reload_config(&mut self) {
        match Config::load() {
            Ok(config) => {
                self.config = config;
                
                // 更新主题设置
                self.theme = Theme::MD3; // 只使用MD3主题
                
                self.theme_mode = match self.config.theme.default_mode.as_str() {
                    "dark" => ThemeMode::Dark,
                    _ => ThemeMode::Light,
                };
                
                // 更新UI参数
                self.time_display_size = self.config.ui.time_display_size;
                self.status_text_size = self.config.ui.status_text_size;
                self.button_height = self.config.ui.button_height;
                self.button_width_ratio = self.config.ui.button_width_ratio;
                self.body_font_size = self.config.ui.body_font_size;
                self.heading_font_size = self.config.ui.heading_font_size;
                self.button_font_size = self.config.ui.button_font_size;
                
                // 重新加载主题管理器并应用当前主题设置
                self.theme_manager = create_default_theme_manager().expect("Failed to reload theme manager");
                
                // 将Theme和ThemeMode枚举转换为字符串
                let theme_str = "md3"; // 只使用MD3主题
                
                let mode_str = match self.theme_mode {
                    ThemeMode::Light => "light",
                    ThemeMode::Dark => "dark",
                };
                
                self.theme_manager.set_theme(theme_str);
                self.theme_manager.set_mode(mode_str);
            }
            Err(e) => {
                eprintln!("Failed to reload config: {}", e);
            }
        }
    }

    fn update_timer(&mut self, _ctx: &egui::Context) {
        if self.is_running == TimerState::Running {
            if let Some(start_time) = self.start_time {
                let elapsed = start_time.elapsed() + self.elapsed_at_pause;
                let total_seconds = if self.is_work_time {
                    self.work_minutes as u64 * 60
                } else {
                    self.break_minutes as u64 * 60
                };
                
                let new_seconds_left = total_seconds.saturating_sub(elapsed.as_secs());
                
                if new_seconds_left == 0 {
                    // 时间到了！暂停计时并显示通知
                    self.is_running = TimerState::Stopped;
                    self.current_time = Duration::from_secs(0);
                    
                    // 播放提示音
                    self.play_notification_sound();
                    
                    // 设置通知内容
                    if self.is_work_time {
                        self.notification_title = "专注时间结束".to_string();
                        self.notification_message = "恭喜完成专注时段！现在开始休息吗？".to_string();
                    } else {
                        self.notification_title = "休息时间结束".to_string();
                        self.notification_message = "休息结束！现在开始新的专注时段吗？".to_string();
                    }
                    
                    self.show_notification = true;
                } else {
                    self.current_time = Duration::from_secs(new_seconds_left);
                }
            }
        }
    }
    
    fn get_primary_color(&self) -> egui::Color32 {
        self.theme_manager.get_primary_color(self.theme_mode)
    }
    
    fn get_secondary_color(&self) -> egui::Color32 {
        self.theme_manager.get_secondary_color(self.theme, self.theme_mode)
    }

    fn get_surface_color(&self) -> egui::Color32 {
        self.theme_manager.get_surface_color(self.theme, self.theme_mode)
    }
    
    fn get_surface_variant_color(&self) -> egui::Color32 {
        self.theme_manager.get_surface_variant_color(self.theme, self.theme_mode)
    }
    
    fn get_on_surface_color(&self) -> egui::Color32 {
        self.theme_manager.get_on_surface_color(self.theme, self.theme_mode)
    }
    
    fn get_on_surface_variant_color(&self) -> egui::Color32 {
        self.theme_manager.get_on_surface_variant_color(self.theme, self.theme_mode)
    }
    
    fn get_error_color(&self) -> egui::Color32 {
        self.theme_manager.get_error_color(self.theme, self.theme_mode)
    }
    
    fn get_outline_color(&self) -> egui::Color32 {
        self.theme_manager.get_outline_color(self.theme, self.theme_mode)
    }
    
    fn get_background_color(&self) -> egui::Color32 {
        self.theme_manager.get_background_color(self.theme, self.theme_mode)
    }
    
    fn get_on_background_color(&self) -> egui::Color32 {
        self.theme_manager.get_on_background_color(self.theme, self.theme_mode)
    }
    
    fn get_on_primary_color(&self) -> egui::Color32 {
        self.theme_manager.get_on_primary_color(self.theme, self.theme_mode)
    }
    
    fn get_on_secondary_color(&self) -> egui::Color32 {
        self.theme_manager.get_on_secondary_color(self.theme, self.theme_mode)
    }
    
    fn get_on_tertiary_color(&self) -> egui::Color32 {
        self.theme_manager.get_on_tertiary_color(self.theme, self.theme_mode)
    }

    // Generate a simple beep sound
    fn generate_beep(&self) -> std::io::Cursor<Vec<u8>> {
        // Generate a simple beep sound (440Hz for 0.5 seconds)
        let sample_rate: u32 = 44100;
        let duration = 0.5; // seconds
        let frequency = 440.0; // Hz
        let amplitude = 0.3;

        let mut samples = Vec::new();
        for i in 0..(sample_rate as f64 * duration) as usize {
            let t = i as f64 / sample_rate as f64;
            let sample = (amplitude * f64::sin(2.0 * std::f64::consts::PI * frequency * t)) as f32;
            samples.push(sample);
            samples.push(sample); // Stereo
        }

        // Create a simple WAV file in memory
        let mut wav_data = Vec::new();
        
        // WAV header
        // RIFF header
        wav_data.extend_from_slice(b"RIFF");
        let data_size = (samples.len() * std::mem::size_of::<f32>()) as u32;
        let file_size = data_size + 36;
        wav_data.extend_from_slice(&file_size.to_le_bytes());
        wav_data.extend_from_slice(b"WAVE");
        
        // fmt subchunk
        wav_data.extend_from_slice(b"fmt ");
        wav_data.extend_from_slice(&16u32.to_le_bytes()); // subchunk1 size
        wav_data.extend_from_slice(&1u16.to_le_bytes()); // audio format (1 = PCM)
        wav_data.extend_from_slice(&2u16.to_le_bytes()); // number of channels (stereo)
        wav_data.extend_from_slice(&sample_rate.to_le_bytes()); // sample rate
        let byte_rate: u32 = sample_rate * 2 * 4; // sample_rate * channels * bits_per_sample/8
        wav_data.extend_from_slice(&byte_rate.to_le_bytes());
        wav_data.extend_from_slice(&4u16.to_le_bytes()); // block align (channels * bits_per_sample/8)
        wav_data.extend_from_slice(&32u16.to_le_bytes()); // bits per sample
        
        // data subchunk
        wav_data.extend_from_slice(b"data");
        wav_data.extend_from_slice(&data_size.to_le_bytes());
        for sample in &samples {
            // Convert f32 to bytes properly
            let bytes = sample.to_le_bytes();
            wav_data.extend_from_slice(&bytes);
        }

        std::io::Cursor::new(wav_data)
    }
    
    fn play_notification_sound(&mut self) {
        if let Some(ref sink) = self.sink {
            // Generate and play beep sound
            let cursor = self.generate_beep();
            if let Ok(source) = rodio::Decoder::new(cursor) {
                sink.set_volume(self.volume); // Apply volume setting
                sink.stop(); // Stop any currently playing sounds
                sink.append(source);
                sink.play();
            }
        }
    }
    
    /// Updates the timer display based on current settings
    fn update_timer_display(&mut self) {
        if self.is_work_time {
            self.current_time = Duration::from_secs(self.work_minutes as u64 * 60);
        } else {
            self.current_time = Duration::from_secs(self.break_minutes as u64 * 60);
        }
    }
    
    fn apply_theme(&self, ctx: &egui::Context) {
        let theme = match self.theme_mode {
            ThemeMode::Light => {
                // Material Design 3 Light theme
                let mut visuals = egui::Visuals::light();
                
                // 根据不同主题设置背景色
                let background_color = match self.theme {
                    Theme::Green => {
                        // 绿色主题使用浅绿色背景
                        egui::Color32::from_rgb(240, 255, 240)
                    },
                    Theme::Purple => {
                        // 紫色主题使用浅紫色背景
                        egui::Color32::from_rgb(250, 240, 255)
                    },
                    _ => {
                        // 其他主题使用默认背景色
                        self.get_background_color()
                    }
                };
                
                visuals.window_fill = background_color;
                visuals.panel_fill = background_color;
                visuals.extreme_bg_color = background_color;
                visuals.widgets.noninteractive.bg_fill = self.get_surface_color();
                
                // MD3 button styling following MD3 specifications
                visuals.widgets.inactive.bg_fill = self.get_surface_variant_color(); // Surface variant for filled buttons when inactive
                visuals.widgets.inactive.fg_stroke.color = self.get_on_surface_variant_color(); // On-surface variant for text
                visuals.widgets.hovered.bg_fill = self.get_primary_color().linear_multiply(0.08); // 8% primary for hover state
                visuals.widgets.hovered.fg_stroke.color = self.get_on_surface_color(); // On-surface for text
                visuals.widgets.active.bg_fill = self.get_primary_color().linear_multiply(0.12); // 12% primary for active state
                visuals.widgets.active.fg_stroke.color = self.get_primary_color(); // Primary color for active text/icon
                
                visuals.override_text_color = Some(self.get_on_surface_color());
                
                // Set up colors for various UI elements following MD3
                let primary_color = self.get_primary_color();
                visuals.selection.bg_fill = self.get_primary_color().linear_multiply(0.12); // 12% primary for selection
                visuals.hyperlink_color = primary_color;
                visuals.widgets.noninteractive.fg_stroke.color = self.get_on_surface_color();
                visuals.extreme_bg_color = self.get_surface_variant_color(); // Surface variant for extreme backgrounds
                visuals.error_fg_color = self.get_error_color(); // Error color
                
                visuals
            },
            ThemeMode::Dark => {
                // Material Design 3 Dark theme
                let mut visuals = egui::Visuals::dark();
                visuals.window_fill = self.get_surface_color();
                visuals.panel_fill = self.get_surface_color();
                visuals.extreme_bg_color = self.get_surface_color();
                visuals.widgets.noninteractive.bg_fill = self.get_surface_color();
                
                // MD3 button styling following MD3 specifications
                visuals.widgets.inactive.bg_fill = self.get_surface_variant_color(); // Surface variant for filled buttons when inactive
                visuals.widgets.inactive.fg_stroke.color = self.get_on_surface_variant_color(); // On-surface variant for text
                visuals.widgets.hovered.bg_fill = self.get_primary_color().linear_multiply(0.08); // 8% primary for hover state
                visuals.widgets.hovered.fg_stroke.color = self.get_on_surface_color(); // On-surface for text
                visuals.widgets.active.bg_fill = self.get_primary_color().linear_multiply(0.12); // 12% primary for active state
                visuals.widgets.active.fg_stroke.color = self.get_primary_color(); // Primary color for active text/icon
                
                visuals.override_text_color = Some(self.get_on_surface_color());
                
                // Set up colors for various UI elements following MD3
                let primary_color = self.get_primary_color();
                visuals.selection.bg_fill = self.get_primary_color().linear_multiply(0.12); // 12% primary for selection
                visuals.hyperlink_color = primary_color;
                visuals.widgets.noninteractive.fg_stroke.color = self.get_on_surface_color();
                visuals.extreme_bg_color = self.get_surface_variant_color(); // Surface variant for extreme backgrounds
                visuals.error_fg_color = self.get_error_color(); // Error color
                
                visuals
            }
        };
        
        ctx.set_visuals(theme);
    }
    
    fn draw_gradient_background(&self, ui: &mut egui::Ui) {
        let rect = ui.max_rect();
        let painter = ui.painter();
        
        // 使用纯色背景，移除光晕效果
        let background_color = self.get_surface_color();
        
        // 绘制纯色背景矩形
        painter.rect_filled(
            rect,
            egui::CornerRadius::same(0),
            background_color
        );
    }
    
    // Apply custom font sizes to the UI context
    fn apply_custom_fonts(&self, ctx: &egui::Context) {
        let mut style = (*ctx.style()).clone();
        style.text_styles = [
            (egui::TextStyle::Small, egui::FontId::new(self.body_font_size * 0.7, egui::FontFamily::Proportional)),
            (egui::TextStyle::Body, egui::FontId::new(self.body_font_size, egui::FontFamily::Proportional)),
            (egui::TextStyle::Button, egui::FontId::new(self.button_font_size, egui::FontFamily::Proportional)),
            (egui::TextStyle::Heading, egui::FontId::new(self.heading_font_size, egui::FontFamily::Proportional)),
            (egui::TextStyle::Monospace, egui::FontId::new(self.body_font_size * 0.8, egui::FontFamily::Monospace)),
        ].into();
        ctx.set_style(style);
    }
    
    // Create animated button with hover and press effects
    fn create_animated_button(&self, text: &str, is_hovered: bool, is_pressed: bool, base_color: egui::Color32) -> egui::Button<'_> {
        let animated_color = if is_pressed {
            // Darken the color when pressed for a pressed effect
            base_color.linear_multiply(0.8)
        } else if is_hovered {
            // Lighten the color on hover for a subtle animation effect
            base_color.linear_multiply(1.2)
        } else {
            base_color
        };
        
        let scale = if is_pressed { 0.95 } else { 1.0 };
        
        egui::Button::new(egui::RichText::new(text).size(self.button_font_size))
            .fill(animated_color)
            .stroke(egui::Stroke::new(0.0, egui::Color32::TRANSPARENT))
            .corner_radius(4.0)
            .min_size(egui::Vec2::new(0.0, self.button_height * scale))
    }
    
    // Create animated outlined button with hover and press effects
    fn create_animated_outlined_button(&self, text: &str, is_hovered: bool, is_pressed: bool) -> egui::Button<'_> {
        let stroke_color = if is_pressed {
            self.get_primary_color().linear_multiply(0.8)
        } else if is_hovered {
            self.get_primary_color()
        } else {
            self.get_outline_color()
        };
        
        let fill_color = if is_pressed {
            self.get_primary_color().linear_multiply(0.2)
        } else if is_hovered {
            self.get_primary_color().linear_multiply(0.1)
        } else {
            egui::Color32::TRANSPARENT
        };
        
        let scale = if is_pressed { 0.95 } else { 1.0 };
        
        egui::Button::new(egui::RichText::new(text).size(self.button_font_size))
            .fill(fill_color)
            .stroke(egui::Stroke::new(1.0, stroke_color))
            .corner_radius(4.0)
            .min_size(egui::Vec2::new(0.0, self.button_height * scale))
    }
    

}

impl eframe::App for PomodoroApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        // Update animation timing
        let now = Instant::now();
        if let Some(last) = self.last_update {
            // Calculate time delta for animations
            let _delta = now.duration_since(last);
            // We can use this delta for smooth animations if needed
        }
        self.last_update = Some(now);
        
        self.update_timer(ctx);
        
        // Apply theme based on current theme mode
        self.apply_theme(ctx);
        
        // Apply custom fonts
        self.apply_custom_fonts(ctx);
        
        // Refresh UI every second to update the timer display
        if self.is_running == TimerState::Running {
            ctx.request_repaint_after(Duration::from_secs(1));
        }
        
        // Request repaint for animations
        ctx.request_repaint_after(Duration::from_millis(16)); // ~60 FPS
        
        // 显示通知对话框
        if self.show_notification {
            // Center window on screen
            let window_size = egui::Vec2::new(300.0, 200.0);
            
            egui::Window::new(&self.notification_title)
                .collapsible(false)
                .resizable(false)
                .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
                .fixed_size(window_size)
                .show(ctx, |ui| {
                    ui.label(&self.notification_message);
                    ui.add_space(10.0);
                    
                    // Only show action buttons for timer notifications, not for "About" dialog
                    if self.notification_title != "关于米多计时" {
                        ui.horizontal(|ui| {
                            if ui.button("开始休息").clicked() {
                                self.show_notification = false;
                                self.is_work_time = false;
                                self.current_time = Duration::from_secs(self.break_minutes as u64 * 60);
                                self.is_running = TimerState::Running; // Start immediately
                                self.start_time = Some(Instant::now()); // Set start time
                            }
                            
                            if ui.button("继续专注").clicked() {
                                self.show_notification = false;
                                self.is_work_time = true;
                                self.current_time = Duration::from_secs(self.work_minutes as u64 * 60);
                                self.is_running = TimerState::Running; // Start immediately
                                self.start_time = Some(Instant::now()); // Set start time
                            }
                            
                            if ui.button("延长5分钟").clicked() {
                                self.show_notification = false;
                                if self.is_work_time {
                                    self.work_minutes += 5;
                                    self.current_time = Duration::from_secs(self.work_minutes as u64 * 60);
                                } else {
                                    self.break_minutes += 5;
                                    self.current_time = Duration::from_secs(self.break_minutes as u64 * 60);
                                }
                                self.is_running = TimerState::Running; // Start immediately
                                self.start_time = Some(Instant::now()); // Set start time
                            }
                        });
                    } else {
                        // For "About" dialog, just show an OK button
                        ui.horizontal(|ui| {
                            if ui.button("确定").clicked() {
                                self.show_notification = false;
                            }
                        });
                    }
                });
        }
        
        // 添加菜单栏
        egui::TopBottomPanel::top("menu_bar").show(ctx, |ui| {
            egui::menu::bar(ui, |ui| {
                ui.menu_button("设置", |ui| {
                    ui.menu_button("主题设置", |ui| {
                        ui.label("选择主题颜色:");
                        ui.horizontal(|ui| {
                            // 只显示MD3主题选项
                        let _ = ui.selectable_label(true, "MD3");
                        });
                        
                        ui.separator();
                        
                        ui.label("选择主题模式:");
                        ui.horizontal(|ui| {
                            if ui.selectable_label(self.theme_mode == ThemeMode::Light, "亮色").clicked() {
                                self.theme_mode = ThemeMode::Light;
                            }
                            if ui.selectable_label(self.theme_mode == ThemeMode::Dark, "暗色").clicked() {
                                self.theme_mode = ThemeMode::Dark;
                            }
                        });
                    });
                    
                    ui.menu_button("音量设置", |ui| {
                        ui.label("提示音量:");
                        ui.add(egui::Slider::new(&mut self.volume, 0.0..=1.0).text("音量"));
                    });
                    
                    ui.separator();
                    
                    if ui.button("刷新配置").clicked() {
                        self.reload_config();
                    }
                });
                ui.menu_button("帮助", |ui| {
                    if ui.button("关于").clicked() {
                        // Set up the about dialog
                        self.notification_title = "关于米多计时".to_string();
                        self.notification_message = "米多计时 (Mido Timer) v0.1.0\n\n专为提高专注力而设计的番茄工作法计时器\n\n采用 Rust 语言和 egui 框架开发\n\n开源许可证: MIT".to_string();
                        self.show_notification = true;
                    }
                });
                if ui.button("退出").clicked() {
                    self.should_exit = true;
                }
                
                // 添加弹性空间，将主题切换按钮推到最右侧
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    // Theme toggle button with sun/moon icon
                    let theme_icon = if self.theme_mode == ThemeMode::Light {
                        "🌙" // Moon icon for dark mode
                    } else {
                        "☀" // Sun icon for light mode (使用不带额外符号的太阳图标)
                    };
                    
                    if ui.button(theme_icon).clicked() {
                        // Toggle between light and dark mode
                        self.theme_mode = if self.theme_mode == ThemeMode::Light {
                            ThemeMode::Dark
                        } else {
                            ThemeMode::Light
                        };
                    }
                });
            });
        });
        
        egui::CentralPanel::default().show(ctx, |ui| {
            // Draw gradient background
            self.draw_gradient_background(ui);
            
            ui.vertical_centered(|ui| {
                ui.add_space(20.0);
                
                // ui.heading("米多计时");
                
                ui.add_space(30.0);
                
                // Timer display
                let time_text = format!(
                    "{:02}:{:02}",
                    self.current_time.as_secs() / 60,
                    self.current_time.as_secs() % 60
                );
                
                let status_text = if self.is_work_time {
                    "专注时间"
                } else {
                    "休息时间"
                };
                
                ui.vertical_centered(|ui| {
                    ui.label(egui::RichText::new(&time_text)
                        .size(self.time_display_size)  // 使用配置的字体大小
                        .color(self.get_primary_color())
                        .strong()    // Bold font
                        .family(egui::FontFamily::Proportional)); // Use proportional font for better appearance
                    
                    ui.add_space(10.0);
                    
                    ui.label(egui::RichText::new(status_text)
                        .size(self.status_text_size)  // 使用配置的字体大小
                        .color(self.get_primary_color())
                        .strong()    // Bold font
                        .family(egui::FontFamily::Proportional)); // Use proportional font for better appearance
                });
                
                ui.add_space(30.0);
                
                // Controls - Centered horizontally
                ui.vertical_centered(|ui| {
                    ui.horizontal(|ui| {
                        let button_width = ui.available_width() * self.button_width_ratio; // 使用配置的宽度比例
                        
                        // Start button - disabled when timer is running
                        if self.is_running == TimerState::Running {
                            // Disabled state - make it visually distinct
                            let disabled_start_button = egui::Button::new("开始")
                                .fill(self.get_primary_color().linear_multiply(0.5)) // 使用主题主色但降低亮度表示禁用状态
                                .stroke(egui::Stroke::new(0.0, egui::Color32::TRANSPARENT))
                                .corner_radius(4.0);
                            ui.add_sized([button_width, self.button_height], disabled_start_button.sense(egui::Sense::hover())); // 使用配置的高度
                        } else {
                            // 启用状态的开始按钮，使用主题主色并添加动画效果
                            let start_button = self.create_animated_button(
                                "开始", 
                                self.start_button_hover, 
                                self.start_button_press, 
                                self.get_primary_color()
                            ).min_size([button_width, self.button_height].into()); // 使用配置的高度
                            let start_response = ui.add(start_button);
                            
                            // Check for hover state for animation
                            self.start_button_hover = start_response.hovered();
                            
                            if start_response.clicked() {
                                self.is_running = TimerState::Running;
                                self.start_time = Some(Instant::now());
                            }
                        }
                        
                        ui.add_space(10.0);
                        
                        // Pause button - disabled when timer is not running
                        if self.is_running != TimerState::Running {
                            // Disabled state - make it visually distinct
                            let disabled_pause_button = egui::Button::new("暂停")
                                .fill(self.get_secondary_color().linear_multiply(0.5)) // 使用次色但降低亮度表示禁用状态
                                .stroke(egui::Stroke::new(0.0, egui::Color32::TRANSPARENT))
                                .corner_radius(4.0);
                            ui.add_sized([button_width, self.button_height], disabled_pause_button.sense(egui::Sense::hover())); // 使用配置的高度
                        } else {
                            // 启用状态的暂停按钮，使用次色并添加动画效果
                            let pause_button = self.create_animated_button(
                                "暂停", 
                                self.pause_button_hover, 
                                self.pause_button_press, 
                                self.get_secondary_color()
                            ).min_size([button_width, self.button_height].into()); // 使用配置的高度
                            let pause_response = ui.add(pause_button);
                            
                            // Check for hover state for animation
                            self.pause_button_hover = pause_response.hovered();
                            
                            if pause_response.clicked() {
                                self.is_running = TimerState::Paused;
                                if let Some(start_time) = self.start_time {
                                    self.elapsed_at_pause = start_time.elapsed();
                                }
                            }
                        }
                        
                        ui.add_space(10.0);
                        
                        // 重置按钮使用轮廓样式并添加动画效果
                        let reset_button = self.create_animated_outlined_button(
                            "重置", 
                            self.reset_button_hover,
                            self.reset_button_press
                        ).min_size([button_width, self.button_height].into()); // 使用配置的高度
                        let reset_response = ui.add(reset_button);
                        
                        // Check for hover state for animation
                        self.reset_button_hover = reset_response.hovered();
                        
                        if reset_response.clicked() {
                            self.is_running = TimerState::Stopped;
                            self.is_work_time = true;
                            
                            match self.preset {
                                Preset::TwentyFiveFive => {
                                    self.work_minutes = 25;
                                    self.break_minutes = 5;
                                    self.work_input = "25".to_string();
                                    self.break_input = "5".to_string();
                                }
                                Preset::FortyFiveFifteen => {
                                    self.work_minutes = 45;
                                    self.break_minutes = 15;
                                    self.work_input = "45".to_string();
                                    self.break_input = "15".to_string();
                                }
                                Preset::Custom => {
                                    self.work_minutes = self.work_input.parse().unwrap_or(25);
                                    self.break_minutes = self.break_input.parse().unwrap_or(5);
                                }
                            }
                            
                            if self.is_work_time {
                                self.current_time = Duration::from_secs(self.work_minutes as u64 * 60);
                            } else {
                                self.current_time = Duration::from_secs(self.break_minutes as u64 * 60);
                            }
                            
                            self.start_time = None;
                            self.elapsed_at_pause = Duration::new(0, 0);
                        }
                    });
                });

                ui.add_space(30.0);
                
                // Settings section
                ui.group(|ui| {
                    ui.heading("计时设置");
                    
                    ui.horizontal(|ui| {
                        // Preset buttons
                        if ui.selectable_value(&mut self.preset, Preset::TwentyFiveFive, "25/5").clicked() {
                            self.work_minutes = 25;
                            self.break_minutes = 5;
                            self.work_input = "25".to_string();
                            self.break_input = "5".to_string();
                            self.update_timer_display();
                            // Prepare timer immediately
                            self.is_running = TimerState::Stopped;
                            self.is_work_time = true;
                            self.current_time = Duration::from_secs(self.work_minutes as u64 * 60);
                            self.start_time = None;
                            self.elapsed_at_pause = Duration::new(0, 0);
                        }
                        if ui.selectable_value(&mut self.preset, Preset::FortyFiveFifteen, "45/15").clicked() {
                            self.work_minutes = 45;
                            self.break_minutes = 15;
                            self.work_input = "45".to_string();
                            self.break_input = "15".to_string();
                            self.update_timer_display();
                            // Prepare timer immediately
                            self.is_running = TimerState::Stopped;
                            self.is_work_time = true;
                            self.current_time = Duration::from_secs(self.work_minutes as u64 * 60);
                            self.start_time = None;
                            self.elapsed_at_pause = Duration::new(0, 0);
                        }
                        if ui.selectable_value(&mut self.preset, Preset::Custom, "自定义").clicked() {
                            // For custom preset, we keep the current values but update the display
                            if let Ok(work) = self.work_input.parse::<u16>() {
                                if work > 0 && work <= 60 {
                                    self.work_minutes = work;
                                }
                            }
                            if let Ok(break_time) = self.break_input.parse::<u16>() {
                                if break_time > 0 && break_time <= 30 {
                                    self.break_minutes = break_time;
                                }
                            }
                            self.update_timer_display();
                            // Prepare timer immediately
                            self.is_running = TimerState::Stopped;
                            self.is_work_time = true;
                            self.current_time = Duration::from_secs(self.work_minutes as u64 * 60);
                            self.start_time = None;
                            self.elapsed_at_pause = Duration::new(0, 0);
                            // Show custom settings when custom preset is selected
                            self.show_custom_settings = true;
                        }

                    });
                    
                    // Custom settings if selected or manually shown
                    if self.preset == Preset::Custom && self.show_custom_settings {
                        ui.horizontal(|ui| {
                            ui.label("专注 (分钟):");
                            ui.text_edit_singleline(&mut self.work_input);
                            
                            ui.label("休息 (分钟):");
                            ui.text_edit_singleline(&mut self.break_input);
                        });
                        
                        ui.horizontal(|ui| {
                            ui.add_space(ui.available_width() * 0.3);
                            if ui.button("确认设置").clicked() {
                                if let Ok(work_minutes) = self.work_input.parse::<u16>() {
                                    if work_minutes > 0 && work_minutes <= 60 {
                                        self.work_minutes = work_minutes;
                                    }
                                }
                                if let Ok(break_minutes) = self.break_input.parse::<u16>() {
                                    if break_minutes > 0 && break_minutes <= 30 {
                                        self.break_minutes = break_minutes;
                                    }
                                }
                                self.update_timer_display();
                                // Prepare timer immediately
                                self.is_running = TimerState::Stopped;
                                self.is_work_time = true;
                                self.current_time = Duration::from_secs(self.work_minutes as u64 * 60);
                                self.start_time = None;
                                self.elapsed_at_pause = Duration::new(0, 0);
                                // Hide custom settings after confirmation
                                self.show_custom_settings = false;
                            }
                        });
                    }

                });
                
                ui.add_space(20.0);
                
                // Theme selector
                ui.group(|ui| {
                    ui.heading("主题");
                    
                    ui.horizontal(|ui| {
                        // 只显示MD3主题选项
                        let _ = ui.selectable_label(true, "MD3");
                    });
                });
                
                ui.add_space(20.0);
                
                ui.separator();
                
                ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| {
                    ui.label("专为米多设计 ❤️");
                });
            });
        });
        
        // Check if we should exit the application
        if self.should_exit {
            std::process::exit(0);
        }
    }
}